// pages/createPatient/create/create.js
// 新建孩子信息
const app = getApp()
const api = require('../../../config/api')
const request = require('../../../utils/request')
const { parse } = require('../../../utils/util')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isEdit: 0,
    isEditIdCard: false,
    patientInfo: {
      age: '',
      allergy: '',
      birthday: '',
      contact: '',
      contactRelationType: '',
      contactTel: '',
      familyHistory: '',
      idCard: '',
      nation: '',
      pastHistory: '',
      patientName: '',
      personalHistory: '',
      postnatalFactors: null,
      prenatalFactors: null,
      productionFactors: null,
      relation: '',
      sex: '',
    },
    today: '',
    startDate: '',
    showModalStatus: false,
    paddingBottom: app.kBottomSafeHeight + 43,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const date = new Date()
    //获取年份
    let Y = date.getFullYear()
    //获取月份
    let M =
      date.getMonth() + 1 < 10
        ? '0' + (date.getMonth() + 1)
        : date.getMonth() + 1
    //获取当日日期
    let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

    let date1 = this.gap(14)
    let startDate = date1.toLocaleString().split(' ')[0].replace(/\//g, '-')

    this.setData({
      today: Y + '-' + M + '-' + D,
      startDate: startDate,
    })
    if (options.patientInfo) {
      const patientInfo = parse(options.patientInfo)
      this.getPatientDetial(patientInfo.id)
    }
  },
  /**
   * 获取n年前的日期
   * @param {*} n 年数
   */
  gap: function (n) {
    var now = new Date()
    now.setFullYear(now.getFullYear() - n)
    return now
  },
  // 获取患者详情
  getPatientDetial: async function (id) {
    const res = await request.get(api.patientDetail + '/' + id)
    if (res.httpStatus === 200) {
      res.data.birthday = res.data.birthday.substring(0, 10)
      this.setData({
        patientInfo: res.data,
        isEdit: 1,
        isEditIdCard: true,
      })
    }
  },
  // 患者数据绑定
  patientVal(e) {
    let patientInfo = this.data.patientInfo
    const value = e.detail.value
    const key = e.target.dataset.key
    key === 'sex'
      ? (patientInfo[key] = Number(value))
      : (patientInfo[key] = value)
    this.setData({
      patientInfo,
    })
  },

  // 根据身份证号计算性别及出生日期
  idCart(e) {
    let patientInfo = this.data.patientInfo
    const idCard = e.detail.value
    const idCardNo =
      /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    this.setData({
      patientInfo: {
        ...patientInfo,
        idCard,
      },
    })
    if (!idCardNo.test(idCard)) {
      return
    }
    // 截取出生日期
    let birthdayno, birthdaytemp, sexno, sex
    if (idCard.length === 18) {
      birthdayno = idCard.substring(6, 14)
      sexno = idCard.substring(16, 17)
    } else if (idCard.length === 15) {
      birthdaytemp = idCard.substring(6, 12)
      sexno = idCard.substring(14, 15)
      birthdayno = '19' + birthdaytemp
    }
    let birthday =
      birthdayno.substring(0, 4) +
      '-' +
      birthdayno.substring(4, 6) +
      '-' +
      birthdayno.substring(6, 8)
    // 获取性别
    sex = sexno % 2 ? 1 : 2
    this.setData({
      patientInfo: {
        ...patientInfo,
        birthday,
        sex,
        idCard,
      },
    })
  },
  // 民族弹窗
  nation() {
    this.setData({
      showModalStatus: true,
    })
  },
  hideModal() {
    this.setData({
      showModalStatus: false,
    })
  },
  // 选择民族
  chooseNation(val) {
    let patientInfo = this.data.patientInfo
    this.setData({
      patientInfo: {
        ...patientInfo,
        nation: val.currentTarget.dataset.item,
      },
    })
  },

  savaBtnTap() {
    this.setData({
      showModalStatus: false,
    })
  },
  // 下一步
  next: async function () {
    let { patientInfo } = this.data
    // 防止连续触发保存
    if (this.hadSubmit) {
      return
    }
    // 取掉姓名中空格
    patientInfo.patientName = patientInfo.patientName.replace(/\s+/g, '')

    if (!patientInfo.patientName) {
      wx.showToast({
        title: '请填写孩子姓名',
        icon: 'none',
      })
      return
    }

    if (!patientInfo.sex) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none',
      })
      return
    }
    if (!patientInfo.birthday) {
      wx.showToast({
        title: '请选择出生日期',
        icon: 'none',
      })
      return
    }

    if (patientInfo.birthday.indexOf('00:00:00') < 0) {
      patientInfo.birthday = patientInfo.birthday + ' 00:00:00'
    }
    
    this.hadSubmit = true

    // 判断是否为编辑
    if (this.data.isEdit === 0) {
      const res = await request.post(api.savePatient, patientInfo)
      if (res.httpStatus === 200) {
        app.getPatientList()
        wx.showToast({
          title: '新建成功',
        })
        setTimeout(() => {
          app.handleGoPage()
          setTimeout(()=>{
            this.hadSubmit = false
          },1500)
        }, 400)
      }
    } else {
      const res = await request.post(api.updatePatient, patientInfo)
      if (res.httpStatus === 200) {
        app.getPatientList()
        wx.showToast({
          title: '修改成功',
        })
        wx.navigateBack({
          delta: 1,
        })
        this.hadSubmit = false
      }
    }
  },
  // 点击保存
  handleSubmit() {},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
})
